`timescale 1ns / 1ps

module tb_spi_master;

  // spi_master Parameters
  parameter PERIOD = 37;

  // spi_master Inputs
  reg           clk = 0;
  reg           rst_n = 0;
  reg     [7:0] data_in = 0;
  reg           start = 0;
  reg           miso = 0;

  // spi_master Outputs
  wire          sclk;
  wire          mosi;
  wire          cs_n;
  wire          busy;
  wire    [7:0] data_out;

  integer       i;  // Loop variable for multiple byte testing

  // initial begin
  //   forever #(PERIOD / 2) clk = ~clk;
  // end
  always #(PERIOD / 2) clk = ~clk;  // Generate clock signal

  initial begin
    #(PERIOD * 2) rst_n = 1;
  end

  spi_master u_spi_master (
      .clk    (clk),
      .rst_n  (rst_n),
      .data_in(data_in[7:0]),
      .start  (start),
      .miso   (miso),

      .sclk    (sclk),
      .mosi    (mosi),
      .cs_n    (cs_n),
      .busy    (busy),
      .data_out(data_out[7:0])
  );

  initial begin
    // Wait for reset
    #(PERIOD * 10);
    // Test multiple byte SPI communication
    for (i = 0; i < 5; i = i + 1) begin
      data_in = i;  // Send byte i
      start   = 1;  // Start SPI communication
      #(PERIOD);  // Wait for one clock cycle
      start = 0;  // Clear start signal

      // Simulate MISO data (loopback for testing)
      wait (sclk==0);
      miso  = data_in[7];  // Send MSB first
      repeat (7) begin
        @(negedge sclk);  // Wait for falling edge of SCLK
        data_in = {data_in[6:0], 1'b0};
        miso = data_in[7];  // Shift data for next bit
      end
      // Wait for busy signal to clear
      wait (!busy);
      // Check received data
      $display("Sent: %h, Received: %h", i, data_out);
    end
    $display("Simulation finished successfully.");
    $dumpfile("build/wave.vcd");
    $dumpvars;  // Dump all variables in the testbench
    $finish;
  end

initial begin
    // #(100000000);  // Wait for 10000ms
    // $display("Simulation timeout. Exiting.");
    $dumpfile("build/wave.vcd");
    $dumpvars;  // tb的模块名
    // $finish; // Finish simulation after 1ms
end
endmodule
